package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

var tx_result bool = true
func main(){
	db,err := sql.Open("mysql","vagrant:vagrant@tcp(127.0.0.1:3306)/test1?charset=utf8")
	if err != nil {
		panic(err)
		return
	}
	defer db.Close()

	tx,err := db.Begin()
	defer func() {
		if tx_result {
			tx.Commit()
		} else {
			tx.Rollback()
		}
	}()

	if err != nil {
		fmt.Println("无法开启事务")
		return
	}
	insert_sql := "insert into `users` set `name`=?,`pwd` =?,`age`=?"
	stam,err :=tx.Prepare(insert_sql)
	if err != nil{
		fmt.Println("sql语法有误")
		tx_result = false
		return
	}
	defer stam.Close()
	_,err = stam.Exec("jmz","ada3cfs3fcs",33)
	if err != nil{
		fmt.Println("增加有误")
		tx_result = false
	}

	update_sql := "update users set name = ?,age =? where id = ?"
	stam,err =tx.Prepare(update_sql)
	if err != nil{
		fmt.Println("updatesql执行有误")
		tx_result = false
		return
	}
	_,err = stam.Exec("中国1111",99,1)
	if err != nil{
		fmt.Println("执行有误")
		tx_result = false
		return
	}
}
